﻿using Dlpad.Services;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;

namespace Dlpad.Controllers
{
    //字典数据查询与缓存运维 只读查询与缓存管理
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class DictController : ControllerBase
    {
        private readonly IDictDataService _dictDataService;
        private readonly IDictTypeService _dictTypeService;
        private readonly ICacheService _cacheService; 


        public DictController(IDictDataService dictDataService, IDictTypeService dictTypeService, ICacheService cacheService)
        {
            _dictDataService = dictDataService;
            _dictTypeService = dictTypeService;
            _cacheService = cacheService; // 使用缓存服务
        }

        /// <summary>
        /// 根据字典类型获取字典数据
        /// </summary>
        [HttpGet("data/{dictType}")]
        public async Task<ActionResult<List<DictDataResponseDto>>> GetDictData(string dictType)
        {
            try
            {
                var result = await _dictDataService.GetDictDataByTypeAsync(dictType);
                return Ok(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetDictData 错误: {ex.Message}");
                return StatusCode(500, new { error = "获取字典数据失败" });
            }
        }

        /// <summary>
        /// 根据字典类型获取字典选项
        /// </summary>
        [HttpGet("options/{dictType}")]
        public async Task<ActionResult<List<DictOptionDto>>> GetDictOptions(string dictType)
        {
            try
            {
                var result = await _dictDataService.GetDictOptionsAsync(dictType);
                return Ok(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetDictOptions 错误: {ex.Message}");
                return StatusCode(500, new { error = "获取字典选项失败" });
            }
        }

        /// <summary>
        /// 批量获取多个字典类型的选项
        /// </summary>
        [HttpPost("options/batch")]
        public async Task<ActionResult<Dictionary<string, List<DictOptionDto>>>> GetMultipleDictOptions([FromBody] List<string> dictTypes)
        {
            try
            {
                var result = await _dictDataService.GetMultipleDictOptions(dictTypes);
                return Ok(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetMultipleDictOptions 错误: {ex.Message}");
                return StatusCode(500, new { error = "批量获取字典选项失败" });
            }
        }

        /// <summary>
        /// 根据字典标签获取字典值
        /// </summary>
        [HttpGet("value/{dictType}/{dictLabel}")]
        public async Task<ActionResult<string>> GetDictValue(string dictType, string dictLabel)
        {
            try
            {
                var result = await _dictDataService.GetDictValueByLabelAsync(dictType, dictLabel);
                return Ok(result ?? string.Empty);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetDictValue 错误: {ex.Message}");
                return StatusCode(500, new { error = "获取字典值失败" });
            }
        }

        /// <summary>
        /// 根据字典值获取字典标签
        /// </summary>
        [HttpGet("label/{dictType}/{dictValue}")]
        public async Task<ActionResult<string>> GetDictLabel(string dictType, string dictValue)
        {
            try
            {
                var result = await _dictDataService.GetDictLabelByValuesAsync(dictType, dictValue);
                return Ok(result ?? string.Empty);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetDictLabel 错误: {ex.Message}");
                return StatusCode(500, new { error = "获取字典标签失败" });
            }
        }

        /// <summary>
        /// 刷新字典缓存
        /// </summary>
        // DictController.cs 中的刷新缓存方法
        [HttpPost("refresh-cache")]
        public async Task<IActionResult> RefreshCache()
        {
            try
            {
                await _cacheService.ClearAllDictCacheAsync();

                return Ok(new
                {
                    message = "缓存刷新成功",
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"RefreshCache 错误: {ex.Message}");
                return BadRequest(new { message = $"缓存刷新失败：{ex.Message}" });
            }
        }

        [HttpGet("cache-info")]
        public async Task<ActionResult> GetCacheInfo()
        {
            try
            {
                var allTypes = await _dictTypeService.GetAllDictTypesAsync();
                var cacheInfo = new
                {
                    TotalDictTypes = allTypes.Count,
                    CachedDictTypes = allTypes.Select(t => new
                    {
                        DictType = t.DictType,
                        DictName = t.DictName
                    }),
                    Timestamp = DateTime.Now
                };

                return Ok(cacheInfo);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = $"获取缓存信息失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 健康检查端点
        /// </summary>
        [HttpGet("health")]
        public IActionResult HealthCheck()
        {
            return Ok(new
            {
                status = "healthy",
                service = "DictController",
                timestamp = DateTime.Now
            });
        }

        /// <summary>
        /// 修复缓存格式问题
        /// </summary>
        [HttpPost("fix-cache-format")]
        public async Task<ActionResult> FixCacheFormat()
        {
            try
            {
                var results = new List<string>();

                // 清理并重建 all_dict_types 缓存
                var cacheKey = "Dlpad_all_dict_types";
                await _cacheService.RemoveAsync(cacheKey);
                results.Add($"已清理缓存: {cacheKey}");

                // 重新调用获取，让其重新生成正确的缓存
                var dictTypes = await _dictTypeService.GetAllDictTypesAsync();
                results.Add($"重新生成缓存，包含 {dictTypes.Count} 个字典类型");

                return Ok(new
                {
                    Message = "缓存格式修复完成",
                    Results = results,
                    Timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = $"修复缓存失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 详细验证缓存功能
        /// </summary>
        [HttpGet("cache-validation")]
        public async Task<ActionResult> ValidateCacheFunction()
        {
            var validationResults = new List<object>();

            // 测试字典数据缓存
            var dictType = "sys_user_sex";

            // 第一次调用（应该缓存未命中）
            validationResults.Add(new { Step = "第一次调用开始", Time = DateTime.Now });
            var data1 = await _dictDataService.GetDictDataByTypeAsync(dictType);
            validationResults.Add(new { Step = "第一次调用完成", DataCount = data1.Count, Time = DateTime.Now });

            // 短暂等待
            await Task.Delay(100);

            // 第二次调用（应该缓存命中）
            validationResults.Add(new { Step = "第二次调用开始", Time = DateTime.Now });
            var data2 = await _dictDataService.GetDictDataByTypeAsync(dictType);
            validationResults.Add(new { Step = "第二次调用完成", DataCount = data2.Count, Time = DateTime.Now });

            // 验证数据一致性
            var isConsistent = data1.Count == data2.Count &&
                              data1.Select(d => d.DictCode).SequenceEqual(data2.Select(d => d.DictCode));

            // 测试字典类型缓存
            validationResults.Add(new { Step = "字典类型缓存测试开始", Time = DateTime.Now });
            var dictTypes1 = await _dictTypeService.GetAllDictTypesAsync();
            await Task.Delay(100);
            var dictTypes2 = await _dictTypeService.GetAllDictTypesAsync();
            var dictTypesConsistent = dictTypes1.Count == dictTypes2.Count;

            return Ok(new
            {
                Message = "缓存验证完成",
                DictDataCache = new
                {
                    DictType = dictType,
                    FirstCallCount = data1.Count,
                    SecondCallCount = data2.Count,
                    DataConsistent = isConsistent,
                    CacheWorking = isConsistent && data1.Count > 0
                },
                DictTypeCache = new
                {
                    FirstCallCount = dictTypes1.Count,
                    SecondCallCount = dictTypes2.Count,
                    CacheWorking = dictTypesConsistent && dictTypes1.Count > 0
                },
                ValidationSteps = validationResults,
                Timestamp = DateTime.Now
            });
        }

        /// <summary>
        /// 修复缓存类型问题
        /// </summary>
        [HttpPost("fix-cache-type")]
        public async Task<ActionResult> FixCacheType()
        {
            var results = new List<string>();

            try
            {
                // 修复字典数据缓存
                var dictDataKeys = new[] { "sys_user_sex", "sys_show_hide", "sys_normal_disable" };

                foreach (var dictType in dictDataKeys)
                {
                    var cacheKey = $"Dlpad_dict_data_{dictType}";

                    // 删除可能存在的错误缓存
                    await _cacheService.RemoveAsync(cacheKey);
                    results.Add($"已清理缓存: {cacheKey}");

                    // 重新生成缓存
                    var data = await _dictDataService.GetDictDataByTypeAsync(dictType);
                    results.Add($"重新生成 {dictType} 缓存，数据量: {data.Count}");
                }

                // 修复字典类型缓存
                var typeCacheKey = "Dlpad_all_dict_types";
                await _cacheService.RemoveAsync(typeCacheKey);
                results.Add($"已清理缓存: {typeCacheKey}");

                var dictTypes = await _dictTypeService.GetAllDictTypesAsync();
                results.Add($"重新生成字典类型缓存，数据量: {dictTypes.Count}");

                return Ok(new
                {
                    Message = "缓存类型修复完成",
                    Results = results,
                    Timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = $"修复缓存失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 检查缓存类型
        /// </summary>
        [HttpGet("check-cache-types")]
        public async Task<ActionResult> CheckCacheTypes()
        {
            var keysToCheck = new[]
            {
        "Dlpad_all_dict_types",
        "Dlpad_dict_data_sys_user_sex",
        "Dlpad_dict_type_1"
    };

            var results = new List<object>();

            foreach (var key in keysToCheck)
            {
                try
                {
                    // 尝试作为 String 获取
                    var stringValue = await _cacheService.GetStringAsync(key);
                    var existsAsString = !string.IsNullOrEmpty(stringValue);

                    results.Add(new
                    {
                        Key = key,
                        ExistsAsString = existsAsString,
                        StringValueLength = stringValue?.Length ?? 0,
                        Note = existsAsString ? "String 类型" : "不存在或不是 String 类型"
                    });
                }
                catch (Exception ex)
                {
                    results.Add(new
                    {
                        Key = key,
                        Error = ex.Message
                    });
                }
            }

            return Ok(new
            {
                Message = "缓存类型检查完成",
                Results = results,
                Timestamp = DateTime.Now
            });
        }

        
        /// <summary>
        /// 获取缓存初始化状态
        /// </summary>
        [HttpGet("cache-status")]
        public async Task<ActionResult> GetCacheStatus()
        {
            try
            {
                var allTypes = await _dictTypeService.GetAllDictTypesAsync();
                var cacheInfo = new
                {
                    TotalDictTypes = allTypes.Count,
                    CachedDictTypes = allTypes.Select(t => new
                    {
                        DictType = t.DictType,
                        DictName = t.DictName
                    }),
                    CacheInitialized = allTypes.Count > 0, // 如果有数据则认为缓存已初始化
                    Timestamp = DateTime.Now
                };

                return Ok(cacheInfo);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = $"获取缓存状态失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 手动触发缓存预热
        /// </summary>
        [HttpPost("warmup-cache")]
        public async Task<ActionResult> WarmUpCache()
        {
            try
            {
                // 清除现有缓存
                await _cacheService.ClearAllDictCacheAsync();

                // 重新加载所有字典类型
                var dictTypes = await _dictTypeService.GetAllDictTypesAsync();

                // 预加载每个字典类型的数据
                foreach (var dictType in dictTypes)
                {
                    await _dictDataService.GetDictDataByTypeAsync(dictType.DictType);
                }

                return Ok(new
                {
                    message = "缓存预热完成",
                    dictTypesCount = dictTypes.Count,
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = $"缓存预热失败：{ex.Message}" });
            }
        }

        
        /// <summary>
        /// 获取详细的缓存初始化状态
        /// </summary>
        [HttpGet("cache-detail-status")]
        public async Task<ActionResult> GetCacheDetailStatus()
        {
            try
            {
                var allTypes = await _dictTypeService.GetAllDictTypesAsync();
                var cacheDetails = new List<object>();

                int totalCachedDataCount = 0;

                foreach (var dictType in allTypes)
                {
                    try
                    {
                        var dictData = await _dictDataService.GetDictDataByTypeAsync(dictType.DictType);
                        cacheDetails.Add(new
                        {
                            DictType = dictType.DictType,
                            DictName = dictType.DictName,
                            DataCount = dictData.Count,
                            Cached = dictData.Count > 0
                        });
                        totalCachedDataCount += dictData.Count;
                    }
                    catch (Exception ex)
                    {
                        cacheDetails.Add(new
                        {
                            DictType = dictType.DictType,
                            DictName = dictType.DictName,
                            DataCount = 0,
                            Cached = false,
                            Error = ex.Message
                        });
                    }
                }

                var cacheInfo = new
                {
                    TotalDictTypes = allTypes.Count,
                    TotalCachedData = totalCachedDataCount,
                    CacheDetails = cacheDetails,
                    CacheInitialized = allTypes.Count > 0 && totalCachedDataCount > 0,
                    Timestamp = DateTime.Now
                };

                return Ok(cacheInfo);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = $"获取缓存状态失败：{ex.Message}" });
            }
        }
    }
}